#!/usr/bin  python
# _*_ coding:utf-8 _*_
"""
----------------------------------
    File Name: babies
    Description:
        Author: Dell
        Date: 2020/8/6
-----------------------------------
"""

import datetime
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from extensions.auth import JwtAuthorizationAuthentication
from Baby import models
from EducationContent.models import Hospital
from Baby.serializers import baby
from Common.logger import app_log
from Common.response import resp
from extensions import babysense


class BabyView(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def get(self, request, *args, **kwargs):
        try:
            params = request.query_params
            hospital = params["hospital"]
            group = params["group"]
            status = params["status"]
            if hospital != "ALL":
                if group != "ALL":
                    if status != "ALL":
                        baby_query = models.Babies.objects.filter(hospital=hospital, group=group, status=status).all()
                    else:
                        baby_query = models.Babies.objects.filter(hospital=hospital, group=group).all()
                else:
                    if status != "ALL":
                        baby_query = models.Babies.objects.filter(hospital=hospital, status=status).all()
                    else:
                        baby_query = models.Babies.objects.filter(hospital=hospital).all()
            else:
                if group != "ALL":
                    if status != "ALL":
                        baby_query = models.Babies.objects.filter(group=group, status=status).all()
                    else:
                        baby_query = models.Babies.objects.filter(group=group).all()
                else:
                    if status != "ALL":
                        baby_query = models.Babies.objects.filter(status=status).all()
                    else:
                        baby_query = models.Babies.objects.all()

            baby_data = baby.BabyModelSerializer(baby_query, many=True).data
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': baby_data
            })

        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def put(self, request, *args, **kwargs):
        try:
            data = request.data
            baby_data = data["baby"]
            hospital = data["hospital"]
            group = data["group"]
            time_now = datetime.datetime.now()
            baby_id = baby_data.pop("id")
            baby_data["updated_at"] = time_now
            models.Babies.objects.filter(id=baby_id).update(**baby_data)
            """
            requests.put() ----> babysense.check_babay
            more hospital to do
            """
            # hospital_url = Hospital.objects.filter(hospital_name=hospital).values("hospital_url").first()
            # hospital_url = hospital_url["hospital_url"]
            hospital_url = "https://babysense-staging.fsm.northwestern.edu"
            url = hospital_url + babysense.BabySense_Url["check_baby"] + str(baby_id)
            app_log.info("api url --->{}".format(url))
            babysense_data = models.Babies.objects.filter(id=baby_id).values("babysense_id").first()
            if babysense_data:
                babysense_token = babysense_data["babysense_id"]
                gender = baby_data["gender"]
            else:
                babysense_token = ""
                gender = ""
            put_data = {}
            put_data["babysense_id"] = babysense_token
            put_data["gender"] = gender
            app_log.info("================= Babysense api update baby params===============")
            app_log.info(put_data)
            app_log.info("================= Babysense api update baby params===============")
            response = requests.put(url, json=put_data, headers={
                'content-type': 'application/json'
            })
            app_log.info("================= Babysense api update baby===============")
            app_log.info("update baby response --> {}".format(response))
            app_log.info("================= Babysense api update baby===============")
            if response.status_code == "200":
                pass
            else:
                app_log.info("babysense update baby api error:{}".format(resp(1007, {})))
            data = models.UsersBabies.objects.filter(babies_id=baby_id).values("family_id").first()
            family_id = data["family_id"]
            family_baby_data = models.UsersBabies.objects.filter(family_id=family_id).values(
                "babies_id").all().distinct()
            if len(family_baby_data) >= 2:
                for i in family_baby_data:
                    if i["babies_id"] != baby_id:
                        models.Babies.objects.filter(id=i["babies_id"]).update(hospital=hospital, group=group,
                                                                               updated_at=time_now)
            family_parent_data = models.UsersBabies.objects.filter(family_id=family_id).values(
                "users_id").all().distinct()
            for i in family_parent_data:
                models.Users.objects.filter(id=i["users_id"]).update(hospital=hospital, group=group,
                                                                     updated_at=time_now)
            models.UsersBabies.objects.filter(family_id=family_id).update(hospital=hospital, group=group,
                                                                          updated_at=time_now)
            return Response({
                'error_code': 0,
                'message': "Success"
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def delete(self, request, *args, **kwargs):
        try:
            baby_id = request.GET.get("id", "")
            hospital = request.GET.get("hospital", "")
            baby_data = models.Babies.objects.filter(id=baby_id).all()
            if baby_data.exists():
                """
                babysense.delete_baby
                more hospital to do
                """
                # hospital_url = Hospital.objects.filter(hospital_name=hospital).values("hospital_url").first()
                # hospital_url = hospital_url["hospital_url"]
                hospital_url = "https://babysense-staging.fsm.northwestern.edu"
                url = hospital_url + babysense.BabySense_Url["delete_baby"]
                app_log.info("api url --->{}".format(url))
                babysense_id = models.Babies.objects.filter(id=baby_id).values("babysense_id").first()
                if babysense_id:
                    babysense_token = babysense_id["babysense_id"]
                else:
                    babysense_token = ""
                post_data = {"babysense_id": babysense_token}
                app_log.info("================= Babysense api delete baby params===============")
                app_log.info(post_data)
                app_log.info("================= Babysense api delete baby params===============")
                response = requests.post(url, json=post_data, headers={
                    'content-type': 'application/json'
                })
                app_log.info("================= Babysense api delete baby===============")
                app_log.info("delete baby response --> {}".format(response))
                app_log.info("================= Babysense api delete baby===============")
                if response.status_code == "200":
                    pass
                else:
                    app_log.info("babysense delete baby api error:{}".format(resp(1007, {})))
                models.Babies.objects.filter(id=baby_id).delete()
                return Response({
                    'error_code': 0,
                    'message': "Success"
                })
            else:
                return resp(2003, {})
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)


class DischargeView(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def post(self, request, *args, **kwargs):
        """
        to do  more hospital
        babysense.overwrite_discharge()
        params: {babysense_id: babysense_id}
        """
        try:
            request_data = request.data
            baby_id = request_data["id"]
            hospital = request_data["hospital"]
            discharged = request_data["discharged"]
            discharged_time = datetime.datetime.now().strftime("%Y-%m-%d")
            baby_data = models.Babies.objects.filter(id=baby_id).first()
            if baby_data:
                baby_data.discharged = discharged
                baby_data.discharged_at = discharged_time
                baby_data.status = "Discharge"
                baby_data.save()
                # hospital_url = Hospital.objects.filter(hospital_name=hospital).values("hospital_url").first()
                # hospital_url = hospital_url["hospital_url"]
                hospital_url = "https://babysense-staging.fsm.northwestern.edu"
                url = hospital_url + babysense.BabySense_Url["overwrite_discharge"]
                app_log.info("api url --->{}".format(url))
                babysense_id = models.Babies.objects.filter(id=baby_id).values("babysense_id").first()
                if babysense_id:
                    babysense_token = babysense_id["babysense_id"]
                else:
                    babysense_token = ""
                post_data = {"babysense_id": babysense_token}
                app_log.info("================= Babysense api discharge baby params===============")
                app_log.info(post_data)
                app_log.info("================= Babysense api discharge baby params===============")
                response = requests.post(url, json=post_data, headers={
                    'content-type': 'application/json'
                })
                app_log.info("================= Babysense discharge delete baby===============")
                app_log.info("discharge baby response --> {}".format(response))
                app_log.info("================= Babysense discharge delete baby===============")
                if response.status_code == "200":
                    pass
                else:
                    app_log.info("babysense discharge baby api error:{}".format(resp(1007, {})))
                return Response({
                    'error_code': 0,
                    'message': "Success"
                })
            else:
                return resp(2004, {})
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)


class NotValidatedView(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def put(self, request, *args, **kwargs):
        try:
            request_data = request.data
            baby_id = request_data.pop("id")
            hospital = request_data.pop("hospital")
            babysense_id = models.Babies.objects.filter(id=baby_id).values("babysense_id").first()
            if babysense_id:
                babysense_token = babysense_id["babysense_id"]
            else:
                babysense_token = ""
            # hospital_url = Hospital.objects.filter(hospital_name=hospital).values("hospital_url").first()
            # hospital_url = hospital_url["hospital_url"]
            hospital_url = "https://babysense-staging.fsm.northwestern.edu"
            url = hospital_url + babysense.BabySense_Url["delete_baby"]
            app_log.info("api url --->{}".format(url))
            post_data = {"babysense_id": babysense_token}
            app_log.info("================= Babysense api delete baby params===============")
            app_log.info(post_data)
            app_log.info("================= Babysense api delete baby params===============")
            response = requests.post(url, json=post_data, headers={
                'content-type': 'application/json'
            })
            app_log.info("================= Babysense api delete baby===============")
            app_log.info("api delete baby response --> {}".format(response))
            app_log.info("================= Babysense api delete baby===============")
            if response.status_code == "200":
                url = hospital_url + babysense.BabySense_Url["create_baby"]
                app_log.info("api url --->{}".format(url))
                app_log.info("================= Babysense api create baby params===============")
                app_log.info(request_data)
                app_log.info("================= Babysense api create baby params===============")
                response = requests.post(url, json=request_data, headers={
                    'content-type': 'application/json'
                })
                app_log.info("================= Babysense api create baby===============")
                app_log.info("create baby response --> {}".format(response))
                app_log.info("================= Babysense api create baby===============")
                if response.status_code == "200":
                    babysense_data = response.json()
                    baby_obj = models.Babies.objects.filter(id=baby_id).first()
                    if "validated" in babysense_data:
                        baby_obj.validated = babysense_data["validated"]
                    else:
                        baby_obj.validated = False
                    baby_obj.babysense_id = babysense_data["babysense_id"]
                    baby_obj.expected_birthday = babysense_data["expected_birthday"]
                    baby_obj.gender = request_data["gender"]
                    baby_obj.save()
                    return Response({
                                'error_code': 0,
                                'message': "Success"
                            })
                else:
                    return resp(1007, {})
            else:
                return resp(1007, {})
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)